//
//  DetailController.m
//  NEWS
//
//  Created by lanou on 16/4/7.
//  Copyright © 2016年 孙金龙. All rights reserved.
//

#import "DetailController.h"
#import "DetailCell.h"
#import "RequestManager.h"
#import "TableViewModel.h"
#import <UIImageView+WebCache.h>
#import "DetailWebView.h"
#define KWidth [UIScreen mainScreen].bounds.size.width
#define KHeight  [UIScreen mainScreen].bounds.size.height
@interface DetailController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
@property (nonatomic,strong)UIView *bigView;// 用来返回上一个界面顺便挡住凤凰网
@property (nonatomic,strong)UITableView *TableView;
@property (nonatomic,strong)UIWebView *webView;
@property (nonatomic,strong)NSMutableArray *titleArray;
@property (nonatomic,strong)NSMutableArray *modelArray;
@property (nonatomic,strong)NSMutableArray *bigModelArray;// 用来装每个分区下的model的数组;
@property (nonatomic,strong)UILabel *countLabel;// 变化的数字的label
@property (nonatomic,strong)UILabel *detailLabel;// 详情文字介绍
@end

@implementation DetailController
// 网络请求
- (void)requestWithUrlString:(NSString *)url
{
    [RequestManager requestWithUrl:url parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSDictionary *body = dic[@"body"];
        NSMutableArray *subjects = [body[@"subjects"] mutableCopy];
        // 判断传进来的url是那种页面的(tableView 或者是 scrollview)
        if (subjects != nil)
        {
            // headView的数据
            NSDictionary *head = subjects[0];
            NSDictionary *content = head[@"content"];
            [subjects removeObjectAtIndex:0];
            
            _titleArray = [NSMutableArray array];
            
            for (NSDictionary *modelArrayDic in subjects) {
                // 有的标头标题是空的让他等于0;
                if (modelArrayDic[@"navTitle"] == nil || [modelArrayDic[@"navTitle"] length]==0)
                {
                    [_titleArray addObject:@"0"];
                }
                else
                {
                    [_titleArray addObject:modelArrayDic[@"navTitle"]];
                }
                _modelArray = [NSMutableArray array];
                for (NSDictionary *modelDic in modelArrayDic[@"podItems"])
                {
                    TableViewModel *model = [[TableViewModel alloc] init];
                    [model setValuesForKeysWithDictionary:modelDic];
                    [_modelArray addObject:model];
                }
                [_bigModelArray addObject:_modelArray];
            }
            [_bigModelArray removeLastObject];
            NSLog(@"==%@",_titleArray);
            // 将数据中的表头图片解析出来赋给image
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 150)];
            [image sd_setImageWithURL:[NSURL URLWithString:content[@"bgImage"]]];
            _TableView.tableHeaderView = image;
        }
        else if([body[@"slides"] count] != 0)
        {
            NSArray *slides = body[@"slides"];// 装scrollview数据的数组
            _modelArray = [NSMutableArray array];
            for (NSDictionary *modelDic in slides)
            {
                TableViewModel *model = [[TableViewModel alloc] init];
                [model setValuesForKeysWithDictionary:modelDic];
                [_modelArray addObject:model];
            }
             [self createScrollWithCount:_modelArray.count];
        }
        
        if (_TableView != nil)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [_TableView reloadData];
            });
        }
    } error:^(NSError *error) {
        
    } requestType:RequestGte];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addView];
    [self requestWithUrlString:_model.ID];
    // 判断传过来的是那种类型的布局tableView webView 或者是其他的
    if ([_model.type isEqualToString:@"topic2"])
    {
        _bigModelArray = [NSMutableArray array];
        _TableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 70, KWidth, KHeight-70) style:UITableViewStylePlain];
        _TableView.dataSource = self;
        _TableView.delegate = self;
        [_TableView registerNib:[UINib nibWithNibName:@"DetailCell"bundle:nil]forCellReuseIdentifier:@"detailCell"];
       [self.view addSubview:_TableView];
    }
    else if ([_model.type isEqualToString:@"doc"])
    {
        UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 70, KWidth, KHeight)];
        webView.backgroundColor = [UIColor whiteColor];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_model.commentsUrl]];
        [webView loadRequest:request];
        [self.view addSubview:webView];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _bigModelArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = _bigModelArray[section];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"detailCell" forIndexPath:indexPath];
    NSArray *array = _bigModelArray[indexPath.section];
    TableViewModel *model = array[indexPath.row];
    cell.model = model;
    return cell;
}

// 点击cell的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailWebView *web = [[DetailWebView alloc] init];
    NSArray *array = _bigModelArray[indexPath.section];
    TableViewModel *model = array[indexPath.row];
    web.model = model;
    [self.nav pushViewController:web animated:YES];
     web.nav = self.nav;
}


// 返回cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

// 返回标头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    // 如果没有标题就把高度返回0(不显示表头)
    if ([_titleArray[section] isEqualToString:@"0"])
    {
        return 0;
    }
    else if ([_titleArray[section] length]==0)
    {
        return 0;
    }
    else
    {
        return 25;
    }
    
}

// 给表头设置标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if ([_titleArray[section] isEqualToString:@"0"])
    {
        return nil;
    }
    return _titleArray[section];
}


// 创建scrollview的方法
- (void)createScrollWithCount:(NSInteger)count
{
    // 上面图片的scrollview
    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KHeight *2/5)];
    scroll.contentSize = CGSizeMake(KWidth *count, scroll.frame.size.height);
    scroll.contentOffset = CGPointMake(0, 0);
    scroll.pagingEnabled = YES;
    scroll.bounces = NO;
    scroll.showsHorizontalScrollIndicator = NO;
    scroll.showsVerticalScrollIndicator = NO;
    scroll.delegate = self;
    
    // 下面文字的scrollview
    UIScrollView *scroll2 = [[UIScrollView alloc] initWithFrame:CGRectMake(0, KHeight*1/2+70, KWidth, KHeight/2)];
    scroll2.bounces = NO;
    scroll2.showsHorizontalScrollIndicator = NO;
    scroll2.showsVerticalScrollIndicator = NO;
    scroll2.contentSize = CGSizeMake(KWidth, KHeight/2);
    scroll2.contentOffset = CGPointMake(0, 0);
    scroll2.backgroundColor = [UIColor blackColor];

    for (int i = 0; i < count; i++)
    {
        UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(KWidth*i, 0, KWidth, scroll.frame.size.height)];
        TableViewModel *model = _modelArray[i];
        [image sd_setImageWithURL:[NSURL URLWithString:model.image]];
        [scroll addSubview:image];
        
    }
    // 里面的标题label
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(5, KHeight*2/5+0, KWidth-60, 60)];
    title.font = [UIFont systemFontOfSize:15];
    title.textColor = [UIColor whiteColor];
    title.numberOfLines = 0;
    TableViewModel *model = _modelArray[0];
    title.text = model.title;
    
    // 变化的数字的label
    _countLabel = [[UILabel alloc] initWithFrame:CGRectMake(KWidth-50, KHeight*2/5+15, 40, 35)];
    _countLabel.textColor = [UIColor whiteColor];
    _countLabel.text = [NSString stringWithFormat:@"1/%ld",_modelArray.count];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 70, KWidth, KHeight*1/2)];
    view.backgroundColor = [UIColor blackColor];
    [view addSubview:scroll];
    [view addSubview:title];
    [view addSubview:_countLabel];
    [self.view addSubview:view];
    
    // 详情文字介绍
    _detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, KWidth-10, 20)];
    _detailLabel.numberOfLines = 0;
    _detailLabel.font = [UIFont systemFontOfSize:15];
    _detailLabel.textColor = [UIColor whiteColor];
    // label 自适应高度
    _detailLabel.text = model.DES;
    CGSize size = CGSizeMake(KWidth, 1000);
    CGRect labelSize = [_detailLabel.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:15] forKey:NSFontAttributeName] context:nil];
    _detailLabel.frame = CGRectMake(5, 0, KWidth-10, labelSize.size.height);    
    [scroll2 addSubview:_detailLabel];
    [self.view addSubview:scroll2];
}

// 装载返回button的大视图
- (void)addView
{
    _bigView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, KWidth, 50)];
    _bigView.backgroundColor = [UIColor whiteColor];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(0, 0, 50, 50);
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_bigView addSubview:button];
    [self.view addSubview:_bigView];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    int a = scrollView.contentOffset.x/KWidth;
    _countLabel.text = [NSString stringWithFormat:@"%d/%ld",a+1,_modelArray.count];
    TableViewModel *model = _modelArray[a];
    _detailLabel.text = model.DES;
    CGSize size = CGSizeMake(KWidth, 1000);
    CGRect labelSize = [_detailLabel.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:15] forKey:NSFontAttributeName] context:nil];
    _detailLabel.frame = CGRectMake(5, 0, KWidth-10, labelSize.size.height);
}


// 返回button
- (void)buttonAction:(UIButton *)button
{
    [self.nav popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
